package com.example.zg.androidnewview;

import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.zg.androidnewview.fragments.Fragment1;
import com.example.zg.androidnewview.fragments.Fragment2;
import com.example.zg.androidnewview.fragments.Fragment3;

import java.util.ArrayList;
import java.util.List;

public class TabLayoutActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private String[] titles=new String[]{"最新","热门","我的"};
    private List<Fragment> fragmentList;
    private MFragmentPagerAdapter fmAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);

        initView();

    }

    private void initView(){
        tabLayout=findViewById(R.id.tabLayout);
        viewPager=findViewById(R.id.viewPager);

        fragmentList=new ArrayList<>();
        fragmentList.add(new Fragment1());
        fragmentList.add(new Fragment2());
        fragmentList.add(new Fragment3());

        fmAdapter=new MFragmentPagerAdapter(getSupportFragmentManager());
        fmAdapter.setFragments(fragmentList);
        viewPager.setAdapter(fmAdapter);
        tabLayout.setupWithViewPager(viewPager,true);
    }


    private class MFragmentPagerAdapter extends FragmentPagerAdapter{
        private List<Fragment> fragments;

        public MFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void setFragments(List<Fragment> fragments){
            this.fragments=fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
